package com.woniu.service.impl;

import cn.hutool.core.codec.Base64Decoder;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.woniu.exception.MyErrorException;
import com.woniu.form.FileUploadForm;
import com.woniu.service.FileService;
import com.woniu.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author LXB
 * @Date 2024/1/5 22:28
 * @Description
 **/
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private TokenUtil tokenUtil;

    @Value("${aliyunOss.endpoint}")
    private String endpoint;

    @Value("${aliyunOss.accessKeyId}")
    private String accessKeyId;

    @Value("${aliyunOss.accessKeySecret}")
    private String accessKeySecret;

    @Value("${aliyunOss.bucketName}")
    private String bucketName;

    @Value("${aliyunOss.filePath}")
    private String filePath;


    /**
     * 上传文件
     * @param form 文件base64
     * @return
     */
    @Override
    public String upload(FileUploadForm form) {

        try {
            String userId = tokenUtil.getUserId();

            // base64转输入流
            byte[] decode = Base64Decoder.decode(form.getFileBase64());
            InputStream is = new ByteArrayInputStream(decode);

            // 文件路径
            String filename = filePath + new SimpleDateFormat("yyyy/MM/dd").format(new Date())
                    +"/avatar"+userId+".jpg" ;

            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId,accessKeySecret);

            // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(bucketName, filename, is);


            // 关闭OSSClient。
            ossClient.shutdown();

            return "https://"+bucketName+"."+endpoint+"/" + filename;
        }catch (Exception e){
            throw new MyErrorException("头像上传失败");
        }


    }
}
